﻿using WebSelfHost.Entity.Sys;
using WebSelfHost.Logic.Sys;
using WebSelfHost.Utility.Core;
using WebSelfHost.Utility.Extension;
using WebSelfHost.Utility.Operator;
using WebSelfHost.Utility.Security;
using WebSelfHost.Utility.Web;
using System;
using System.Collections.Generic;
using System.IO;
using WebSelfHost.Web.Filters; 
using Microsoft.AspNetCore.Mvc;
using WebSelfHost.Entity.WebRequestParms.Sys.Account;
using WebSelfHost.Entity.WebRequestParms;
using WebSelfHost.Utility.Other;
using WebSelfHost.Utility.Files;

#if NETFRAMEWORK
using System.Web.Http;
using OwinSessionMiddleware.WebApi;
using System.Net.Http;
using System.Net;
#else
using Microsoft.AspNetCore.Http;
#endif
namespace WebSelfHost.Web.Controllers.Sys
{
    [HiddenApi]
    public class AccountController : BaseController
    {
        private SysUserLogic userlogic;
        private SysUserLogOnLogic userLogOnLogic;

        public AccountController()
        {
            userlogic = new SysUserLogic();
            userLogOnLogic = new SysUserLogOnLogic();
        }
        /// <summary>
        /// 登录页面视图。
        /// </summary>
        /// <returns></returns>
        [Route("")]
        [Route("account/login")]
        [Route("admin")]
        [Route("admin.html")]
        [HttpGet]
        public ActionResult Login()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("softwareName", GlobalValue.Config.WebSoftwareName);
            return Html("/Sys/Account/Login", dict);
        }

        /// <summary>
        /// 获取验证码图片。
        /// </summary>
        /// <returns></returns> 
        [HttpGet, Route("account/verifyCode")]
        public ActionResult VerifyCode()
        {
            VerifyCode verify = new VerifyCode();
#if NETFRAMEWORK
            Request.SetSessionProperty(Keys.SESSION_KEY_VCODE, verify.Text.ToLower());
#else
            HttpContext.Session.SetString(Keys.SESSION_KEY_VCODE, verify.Text.ToLower());
#endif
            return File(verify.Image, "image/jpeg");

        }




        /// <summary>
        /// 提交登录信息。
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="verifycode">验证码</param>
        /// <returns></returns> 
        [HttpPost, Route("account/login")]
        public ActionResult Login(UserLoginParms user)
        {
            if (user.userName.IsNullOrEmpty() || user.password.IsNullOrEmpty())
            {
                return Error("请求失败，缺少必要参数。");
            }
#if !NETFRAMEWORK
            if (user.verifyCode.ToLower() != HttpContext.Session.GetString(Keys.SESSION_KEY_VCODE))
            {
                if (!GlobalValue.Config.Debug)
                    return Warning("验证码错误，请重新输入。");
            }
#else
            if (user.verifyCode.ToLower() != Request.GetSessionProperty<string>(Keys.SESSION_KEY_VCODE))
            {
                if (!GlobalValue.Config.Debug)
                    return Warning("验证码错误，请重新输入。");
            }
#endif
            var userEntity = userlogic.GetByUserName(user.userName);
            if (userEntity == null)
            {
                return Warning("该账户不存在，请重新输入。");
            }
            if (userEntity.IsEnabled != "1")
            {
                return Warning("该账户已被禁用，请联系管理员。");
            }
            var userLogOnEntity = userLogOnLogic.GetByAccount(userEntity.Id);
            string inputPassword = user.password.DESEncrypt(userLogOnEntity.SecretKey).MD5Encrypt();
            if (inputPassword != userLogOnEntity.Password)
            {
                return Warning("密码错误，请重新输入。");
            }
            else
            {
                Operator operatorModel = new Operator();
                operatorModel.UserId = userEntity.Id;
                operatorModel.Account = userEntity.Account;
                operatorModel.RealName = userEntity.RealName;
                operatorModel.Avatar = userEntity.Avatar;
                operatorModel.CompanyId = userEntity.CompanyId;
                operatorModel.DepartmentId = userEntity.DepartmentId;
                operatorModel.LoginTime = DateTime.Now;
                operatorModel.Token = Guid.NewGuid().ToString().DESEncrypt();
                OperatorProvider.Instance.SetCurrent(Request, operatorModel);
                userLogOnLogic.UpdateLogin(userLogOnEntity);
                return Success();
            }
        }

        /// <summary>
        /// 安全退出系统。
        /// </summary>
        /// <returns></returns> 
        [HttpGet, Route("account/exit")]
        public ActionResult Exit()
        {
            if (OperatorProvider.Instance.GetCurrent(Request) != null)
            {
                OperatorProvider.Instance.Remove(Request);
            }
            return Redirect("/account/login");
        }

        /// <summary>
        /// 锁定登录用户。
        /// </summary>
        /// <returns></returns> 
        [HttpPost, Route("account/lock"), LoginChecked]
        public ActionResult Lock()
        {
            if (OperatorProvider.Instance.GetCurrent(Request) != null)
            {
                OperatorProvider.Instance.Remove(Request);
            }
            return Success();
        }

        /// <summary>
        /// 解锁登录用户。
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns> 
        [HttpPost, Route("account/unlock")]
        public ActionResult Unlock(UserLoginParms user)
        {
            var userEntity = userlogic.GetByUserName(user.userName);
            var userLogOnEntity = userLogOnLogic.GetByAccount(userEntity.Id);
            string inputPassword = user.password.DESEncrypt(userLogOnEntity.SecretKey).MD5Encrypt();
            if (inputPassword != userLogOnEntity.Password)
            {
                return Warning("密码错误，请重新输入。");
            }
            else
            {
                //重新保存用户信息。
                Operator operatorModel = new Operator();
                operatorModel.UserId = userEntity.Id;
                operatorModel.Account = userEntity.Account;
                operatorModel.RealName = userEntity.RealName;
                operatorModel.Avatar = userEntity.Avatar;
                operatorModel.CompanyId = userEntity.CompanyId;
                operatorModel.DepartmentId = operatorModel.DepartmentId;
                operatorModel.LoginTime = DateTime.Now;
                operatorModel.Token = Guid.NewGuid().ToString().DESEncrypt();
                OperatorProvider.Instance.SetCurrent(Request, operatorModel);
            }
            return Success();
        }

        /// <summary>
        /// 账户管理视图。
        /// </summary>
        /// <returns></returns> 
        [HttpGet, Route("account/infoCard"), LoginChecked]
        public ActionResult InfoCard()
        {
            return Html("/Sys/Account/InfoCard");
        }



        /// <summary>
        /// 更新用户基础资料。
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns> 
        [HttpPost, Route("account/infoCard"), LoginChecked]
        public ActionResult InfoCard(SysUser model)
        {
            DateTime defaultDt = DateTime.Today;
            DateTime.TryParse(model.StrBirthday, out defaultDt);
            model.Birthday = defaultDt;
            int row = userlogic.UpdateBasicInfo(model, OperatorProvider.Instance.GetCurrent(Request).Account);
            return row > 0 ? Success() : Error();
        }

        [HttpPost, Route("account/getInfoCardForm"), LoginChecked]
        public ActionResult GetInfoCardForm()
        {
            string userId = OperatorProvider.Instance.GetCurrent(Request).UserId;
            SysUser userEntity = userlogic.Get(userId);
            userEntity.StrBirthday = userEntity.Birthday.Value.ToString("yyyy-MM-dd");
            var userLogOnEntity = userLogOnLogic.GetByAccount(userId);
            return Content(userEntity.ToJson());
        }

        /// <summary>
        /// 上传头像。
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("account/uploadAvatar"), LoginChecked]
#if !NETFRAMEWORK
        public ActionResult UploadAvatar(IFormFile file)
        {
            if (file == null)
            {
                return Error();
            }
            string path = MyEnvironment.WebRootPath("/Uploads/Avatar/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string virtualPath = "/Uploads/Avatar/" + Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            string filePath = MyEnvironment.WebRootPath(virtualPath);
            if (FileUtil.Exists(filePath))
            {
                FileUtil.Delete(filePath);
            }
            FileUtil.Save(file, filePath);
            return Success("上传成功。", virtualPath);
        }
#else
        public ActionResult UploadAvatar()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string path = MyEnvironment.WebRootPath("/Uploads/Avatar/");
            var provider = new WithExtensionMultipartFormDataStreamProvider(path, UUID.StrSnowId);
            var fileData = Request.Content.ReadAsMultipartAsync(provider).Result;
            if (fileData.FileData.Count == 0)
            {
                return Error();
            }
            var file = fileData.FileData[0];
            string virtualPath = "/Uploads/Avatar/" + Path.GetFileName(file.LocalFileName);
            return Success("上传成功", virtualPath);
        }
#endif


        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [Route("account/uploadImage")]
        [HttpPost]
#if !NETFRAMEWORK
        public ActionResult UploadImage(IFormFile file)
        {
            if (file == null)
            {
                return Error();
            }
            string path = MyEnvironment.WebRootPath("/Uploads/Avatar/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string virtualPath = "/Uploads/Avatar/" + Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            string filePath = MyEnvironment.WebRootPath(virtualPath);
            if (FileUtil.Exists(filePath))
            {
                FileUtil.Delete(filePath);
            }
            FileUtil.Save(file, filePath);
            return Success("上传成功。", virtualPath);
        }
#else
        public ActionResult UploadImage()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string path = MyEnvironment.WebRootPath("/Uploads/Avatar/");
            var provider = new WithExtensionMultipartFormDataStreamProvider(path, UUID.StrSnowId);
            var fileData = Request.Content.ReadAsMultipartAsync(provider).Result;
            if (fileData.FileData.Count == 0)
            {
                return Error();
            }
            var file = fileData.FileData[0];
            string virtualPath = "/Uploads/Avatar/" + Path.GetFileName(file.LocalFileName);
            return Success("上传成功", virtualPath);
        }
#endif
        /// <summary>
        /// 加载修改密码界面视图。
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("account/modifyPwd"), LoginChecked]
        public ActionResult ModifyPwd()
        {
            return Html("/Sys/Account/ModifyPwd");
        }

        /// <summary>
        /// 修改密码。
        /// </summary>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <param name="confirmPassword">确认密码</param>
        /// <returns></returns> 
        [HttpPost, Route("account/modifyPwd"), LoginChecked]
        public ActionResult ModifyPwd(UserChangePasswordParms user)
        {
            if (user.oldPassword.IsNullOrEmpty() || user.newPassword.IsNullOrEmpty() || user.confirmPassword.IsNullOrEmpty())
            {
                return Error("请求失败，缺少必要参数。");
            }
            if (!user.newPassword.Equals(user.confirmPassword))
            {
                return Warning("两次密码输入不一致，请重新确认。");
            }
            string userId = OperatorProvider.Instance.GetCurrent(Request).UserId;
            var userLoginEntity = userLogOnLogic.GetByAccount(userId);
            if (user.oldPassword.DESEncrypt(userLoginEntity.SecretKey).MD5Encrypt() != userLoginEntity.Password)
            {
                return Warning("旧密码验证失败。");
            }
            userLoginEntity.Password = user.newPassword.DESEncrypt(userLoginEntity.SecretKey).MD5Encrypt();
            int isSuccess = userLogOnLogic.ModifyPwd(userLoginEntity);
            return isSuccess > 0 ? Success() : Error();
        }

        /// <summary>
        /// 上传打标文件
        /// </summary>
        /// <returns></returns> 
        [HttpPost, Route("uploadMarkFile")]
#if !NETFRAMEWORK
        public ActionResult UploadMarkFile(IFormFile file)
        {
            if (file == null)
            {
                return Error();
            }
            string path = MyEnvironment.WebRootPath("/Uploads/MarkFile/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string virtualPath = "/Uploads/MarkFile/" + UUID.StrSnowId + Path.GetExtension(file.FileName);
            string filePath = MyEnvironment.WebRootPath(virtualPath);
            if (FileUtil.Exists(filePath))
            {
                FileUtil.Delete(filePath);
            }
            FileUtil.Save(file, filePath);
            return Success("上传成功。", virtualPath);
        }
#else
        public ActionResult UploadMarkFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string path = MyEnvironment.WebRootPath("/Uploads/MarkFile/");
            var provider = new WithExtensionMultipartFormDataStreamProvider(path, UUID.StrSnowId);
            var fileData = Request.Content.ReadAsMultipartAsync(provider).Result;
            if (fileData.FileData.Count == 0)
            {
                return Error();
            }
            var file = fileData.FileData[0];
            string virtualPath = "/Uploads/MarkFile/" + Path.GetFileName(file.LocalFileName);
            return Success("上传成功", virtualPath);
        }
#endif


        /// <summary>
        /// 上传打标文件
        /// </summary>
        /// <returns></returns> 
        [HttpPost, Route("uploadNCFile")]
#if !NETFRAMEWORK
        public ActionResult UploadNCFile(IFormFile file)
        {
            if (file == null)
            {
                return Error();
            }
            string path = MyEnvironment.WebRootPath("/Uploads/NCFile/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string virtualPath = "/Uploads/NCFile/" + UUID.StrSnowId + Path.GetExtension(file.FileName);
            string filePath = MyEnvironment.WebRootPath(virtualPath);
            if (FileUtil.Exists(filePath))
            {
                FileUtil.Delete(filePath);
            }
            FileUtil.Save(file, filePath);
            return Success("上传成功。", virtualPath);
        }
#else
        public ActionResult UploadNCFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string path = MyEnvironment.WebRootPath("/Uploads/NCFile/");
            var provider = new WithExtensionMultipartFormDataStreamProvider(path, UUID.StrSnowId);
            var fileData = Request.Content.ReadAsMultipartAsync(provider).Result;
            if (fileData.FileData.Count == 0)
            {
                return Error();
            }
            var file = fileData.FileData[0];
            string virtualPath = "/Uploads/NCFile/" + Path.GetFileName(file.LocalFileName);
            return Success("上传成功", virtualPath);
        }
#endif

        /// <summary>
        /// 系统登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost, Route("app/account/login")]
        public ActionResult AppLogin(UserLoginParms user)// string userName, string password)
        {
            //Logger.OperateInfo($"用户{user.userName}请求登录");
            if (user.userName.IsNullOrEmpty() || user.password.IsNullOrEmpty())
            {
                return Error("请求失败，缺少必要参数。");
            }
            user.password = user.password.MD5Encrypt();
            var userEntity = userlogic.GetByUserName(user.userName);
            if (userEntity == null)
            {
                return Error("该账户不存在，请重新输入。");
            }
            if (userEntity.IsEnabled != "1")
            {
                return Error("该账户已被禁用，请联系管理员。");
            }
            var userLogOnEntity = userLogOnLogic.GetByAccount(userEntity.Id);
            string inputPassword = user.password.DESEncrypt(userLogOnEntity.SecretKey).MD5Encrypt();
            if (inputPassword != userLogOnEntity.Password)
            {
                return Error("密码错误，请重新输入。");
            }
            else
            {
                userLogOnLogic.UpdateLogin(userLogOnEntity);
                return Success("恭喜你，操作成功", userEntity);
            }
        }
        /// <summary>
        /// 更新用户基础资料。
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("app/account/infocard")]
        public ActionResult AppInfoCard(SysUser model)
        {
            DateTime defaultDt = DateTime.Today;
            DateTime.TryParse(model.StrBirthday, out defaultDt);
            model.Birthday = defaultDt;
            int row = userlogic.AppUpdateBasicInfo(model);
            return row > 0 ? Success() : Error();
        }
        [HttpPost, Route("app/account/getUserInfo")]
        public ActionResult GetUserInfo(PrimaryKeyParms parms)
        {
            SysUser userEntity = userlogic.Get(parms.primaryKey);
            return Content(userEntity.ToJson());
        }

        [HttpPost, Route("app/account/modifyPwd")]
        public ActionResult AppModifyPwd(ModifyPasswordParms parms)
        {
            if (parms.oldPassword.IsNullOrEmpty() || parms.newPassword.IsNullOrEmpty() || parms.confirmPassword.IsNullOrEmpty())
            {
                return Error("请求失败，缺少必要参数。");
            }
            if (!parms.newPassword.Equals(parms.confirmPassword))
            {
                return Error("两次密码输入不一致，请重新确认。");
            }
            parms.oldPassword = parms.oldPassword.MD5Encrypt();
            parms.newPassword = parms.newPassword.MD5Encrypt();
            parms.confirmPassword = parms.confirmPassword.MD5Encrypt();

            var userLoginEntity = userLogOnLogic.GetByAccount(parms.userId);
            if (parms.oldPassword.DESEncrypt(userLoginEntity.SecretKey).MD5Encrypt() != userLoginEntity.Password)
            {
                return Error("旧密码验证失败。");
            }
            userLoginEntity.Password = parms.newPassword.DESEncrypt(userLoginEntity.SecretKey).MD5Encrypt();
            int isSuccess = userLogOnLogic.ModifyPwd(userLoginEntity);
            return isSuccess > 0 ? Success() : Error();
        }
    }
}